<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="menuDialogFormRef" :model="state.ruleForm" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级菜单">
							<el-cascader :options="state.menuData"
								:props="{ checkStrictly: true, value: 'id', label: 'title' }" placeholder="请选择上级菜单"
								clearable class="w100" v-model="state.menuSuperior">
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单类型">
							<el-radio-group v-model="state.ruleForm.type">
								<el-radio :label="1">目录</el-radio>
								<el-radio :label="2">菜单</el-radio>
								<el-radio :label="3">按钮</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单名称">
							<el-input v-model="state.ruleForm.title" placeholder="格式：message.router.xxx"
								clearable></el-input>
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.type === 1 || state.ruleForm.type === 2">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由名称">
								<el-input v-model="state.ruleForm.name" placeholder="路由中的 name 值" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由路径">
								<el-input v-model="state.ruleForm.path" placeholder="路由中的 path 值" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="重定向">
								<el-input v-model="state.ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单图标">
								<IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.icon" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="组件路径">
								<el-input v-model="state.ruleForm.component" placeholder="组件路径" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col v-if="state.ruleForm.type == 2" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="链接地址">
								<el-input v-model="state.ruleForm.outLink" placeholder="外链/内嵌时链接地址（http:xxx.com）" clearable
									:disabled="!state.ruleForm.isLink">
								</el-input>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="关联角色">
							<el-select v-model="state.ruleForm.role_id" multiple placeholder="取角色管理" clearable class="w100">
								<el-option v-for="item in state.roleData" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.type === 3">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="权限标识">
								<el-input v-model="state.ruleForm.permission" placeholder="请输入权限标识" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单排序">
							<el-input-number v-model="state.ruleForm.orderNo" controls-position="right" placeholder="请输入排序"
								class="w100" />
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.type === 2">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否隐藏">
								<el-radio-group v-model="state.ruleForm.isHide">
									<el-radio :label="1">隐藏</el-radio>
									<el-radio :label="0">不隐藏</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="页面缓存">
								<el-radio-group v-model="state.ruleForm.isKeepAlive">
									<el-radio :label="1">缓存</el-radio>
									<el-radio :label="0">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否固定">
								<el-radio-group v-model="state.ruleForm.isAffix">
									<el-radio :label="1">固定</el-radio>
									<el-radio :label="0">不固定</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否外链">
								<el-radio-group v-model="state.ruleForm.isLink" :disabled="state.ruleForm.isIframe == 1">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否内嵌">
								<el-radio-group v-model="state.ruleForm.isIframe" @change="onSelectIframeChange">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { i18n } from '/@/i18n/index';
import { useMenuApi } from '/@/api/menu/index';
import { useRoleApi } from '/@/api/role';
import { initBackEndControlRoutes } from "/@/router/backEnd";
import { ElMessage } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义变量内容
const roleApi = useRoleApi()
const menuApi = useMenuApi();

const menuDialogFormRef = ref();
const state = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		id: 0,
		fid: 0,
		type: 2, // 菜单类型
		name: '', // 路由名称
		component: '', // 组件路径
		outLink: "",
		isLink: 0, // 是否外链
		orderNo: 0, // 菜单排序
		path: '', // 路由路径
		redirect: '', // 路由重定向，有子集 children 时
		title: '', // 菜单名称
		icon: '', // 菜单图标
		isHide: 0, // 是否隐藏
		isKeepAlive: 0, // 是否缓存
		isAffix: 0, // 是否固定
		isIframe: 0, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
		role_id: [] as number[], // 权限标识，取角色管理
		permission: '', // 菜单类型为按钮时，权限标识
	},
	menuSuperior: [] as number[], // 上级菜单
	menuData: [] as RouteItems, // 上级菜单数据
	roleData: [] as RowRoleType[], // 角色数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 获取 pinia 中的路由
const fommatMenu = (routes: RouteItems) => {
	const arr: RouteItems = [];
	routes.map((val: RouteItem) => {
		val['title'] = i18n.global.t(val.title as string);
		// val['title'] = val.title;
		arr.push({ ...val });
		if (val.children) fommatMenu(val.children);
	});
	return arr;
};
// 请求菜单
const getMenuData = async () => {
	await menuApi.getMenuNoBtn().then((res) => {
		state.menuData = fommatMenu(res.result);
	})
}
// 打开弹窗
const openDialog = async (type: string, row?: any) => {
	// 清空角色数组
	state.ruleForm.role_id=[];
	state.menuSuperior=[];
	// 获取角色数据
	await getRoleData()
	if (type === 'edit') {
		// 深拷贝
		state.ruleForm = JSON.parse(JSON.stringify(row));
		// 获取所有上级菜单
		getUpperMenu(row.id);
		// 只将id传过去
		state.ruleForm.role_id=[];
		await row.roles.map((v:any)=>state.ruleForm.role_id.push(v.id));
		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
	} else {
		state.ruleForm = { type: 1, icon: "", component: "", fid: 0, id: 0, isAffix: 0, isHide: 0, isIframe: 0, isKeepAlive: 0, isLink: 0, name: "", orderNo: 0, outLink: "", path: "", permission: "", redirect: "", remark: "", role_id: [], title: "" } as MenuItem;
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		// nextTick(() => {
		// 	menuDialogFormRef.value.resetFields();
		// });
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};

// 获取角色列表
const getRoleData = () => {
	roleApi.getAllRoles().then((res) => {
		// console.log(res.result);
		state.roleData = res.result;
	})
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 是否内嵌下拉改变
const onSelectIframeChange = () => {
	if (state.ruleForm.isIframe) state.ruleForm.isLink = 1;
	else state.ruleForm.isLink = 0;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async() => {
	state.ruleForm.fid=state.menuSuperior[state.menuSuperior.length-1];
	if (state.dialog.type === 'add') {
		await addMenu().then(res=>{
			ElMessage.success("新增成功");
		}).catch(err=>{
			ElMessage.warning("新增失败");
		});
	}else{
		await updateMenu().then(res=>{
			ElMessage.success("修改成功");
		}).catch(err=>{
			ElMessage.warning("修改失败");
		});
	}
	closeDialog();
	emit('refresh');
	initBackEndControlRoutes() // 刷新菜单，未进行后端接口测试
};

// 请求新增菜单接口
const addMenu = async() => {
	state.ruleForm.id=NaN;
	await menuApi.addMenu(state.ruleForm);
}
// 请求修改菜单接口
const updateMenu = async() => {
	await menuApi.updateMenu(state.ruleForm);
}

// 页面加载时
onMounted(() => {
	getMenuData();
	// state.menuData=fommatMenu(routesList.value)
});

/**
 * 获取上级菜单
 * [0,2]表示此目录在最根部id/所选择的id
 */
const getUpperMenu=(id:number)=>{
	state.menuSuperior=[];
	menuApi.getUpperLine(id).then(res=>{
		res.result.map((v:any,i:number)=>{
			if(i!=res.result.length-1){
				state.menuSuperior.push(v.id)
			}
		})
	})
	
}

// 暴露变量
defineExpose({
	openDialog,
});
</script>
